package com.linmo.questionmatcher;

public class LevenshteinDistance {
    public static int distance(String s1, String s2) {
        //计算两个字符串的长度
        int len1 = s1.length();
        int len2 = s2.length();

        //创建一个动态规划二维数组
        int[][] dp = new int[len1 + 1][len2 + 1];

        //初始化第一行和第一列的值
        for (int i = 0; i <= len1; i++) {
            dp[i][0] = i; //删除操作
        }
        for (int j = 0; j <= len2; j++) {
            dp[0][j] = j; //插入操作
        }

        //填充动态规划数组的值
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1]; //匹配操作
                } else {
                    dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
                }
            }
        }

        //返回最终的最小编辑距离
        return dp[len1][len2];
    }
}
